package com.springcloudalibaba.apiAsyn.service.impl;

import com.springcloudalibaba.apiAsyn.service.MailService;
import com.springcloudalibaba.baserocketmq.service.RocketMqService;
import com.springcloudalibaba.bclass.base.BaseMailEntity;
import com.springcloudalibaba.bclass.enums.RocketMqDelayLevelEnum;
import com.springcloudalibaba.bclass.constant.RocketMqTopicConstant;
import com.springcloudalibaba.bclass.util.StrUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.concurrent.CompletableFuture;

/**
 * @描述:
 * @作者: lixing
 * @日期 2021/6/6 12:38
 */
@Service
public class MailServiceImpl implements MailService {
    // 发送邮件接口
    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private RocketMqService<BaseMailEntity> rocketMqService;

    /**
     * @描述 发送html格式邮件
     * @作者 lixing
     * @日期 2019/8/11 17:33
     */
    @Override
    public CompletableFuture<Boolean> sendHtmlMail(BaseMailEntity baseMailEntity) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 是否带附件
        MimeMessageHelper mimeMessageHelper;
        if (StrUtil.isEffective(baseMailEntity.getAttachment())) {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); // 开启带附件
            String[] filePaths = baseMailEntity.getAttachment().split(",");
            FileSystemResource file;
            for (String filePath : filePaths) {
                file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                mimeMessageHelper.addAttachment(fileName, file); // 添加附件
            }
        } else {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
        }
        mimeMessageHelper.setSubject(baseMailEntity.getSubject()); // 邮件主题
        mimeMessageHelper.setText(baseMailEntity.getText(), true); // 邮件内容
        mimeMessageHelper.setFrom(baseMailEntity.getSender());  // 发送者
        mimeMessageHelper.setTo(baseMailEntity.getReceiver());  // 接收者

        // TODO 发送邮件
        javaMailSender.send(mimeMessage);
        // TODO RocketMQ异步添加异常日志
        rocketMqService.sendAsyncMsg(RocketMqTopicConstant.LOG_TOPIC_MAIL, baseMailEntity, 10000, RocketMqDelayLevelEnum.SECONDS_ONE.getLevel());
        //
        return CompletableFuture.completedFuture(true);
    }

}
